package com.hdax.dm.utils.request;

import cn.hutool.crypto.asymmetric.RSA;
import com.hdax.dm.constant.tokenConstant;
import io.jsonwebtoken.*;

import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

public class tokenutil {

    //1.声明创建时间
    public static Date createdate = new Date();
    //2.过期时间
    public static Date expreDate =  new Date(createdate.getTime() + 180*60*1000);

    public static String createdToken(Long id, String name) {
        //使用JWT生成token

        //3.生成token
        RSA rsa = new RSA(tokenConstant.tokenkeys.PRIVATE_KEY,null);
        RSAPrivateKey rsaPrivateKey= (RSAPrivateKey) rsa.getPrivateKey();
        JwtBuilder jwtBuilder = Jwts.builder();
        jwtBuilder.claim("username",name)
                .setIssuedAt(createdate)
                .setExpiration(expreDate)
                .setId(id+"")//设置jti,它是JWT的唯一标识
                //生产签名信息
                .signWith(rsaPrivateKey, SignatureAlgorithm.RS256);

        return jwtBuilder.compact();
    }

    public static Claims parserToken(String token) {
        //获取公钥对token字符串进行解密
        RSA rsa = new RSA(null, tokenConstant.tokenkeys.PUBLIC_KEY);
        RSAPublicKey rsaPublicKey= (RSAPublicKey) rsa.getPublicKey();

        //JWT构建者
        JwtParserBuilder parserBuilder = Jwts.parserBuilder();
        parserBuilder.setSigningKey(rsaPublicKey);

        JwtParser jwtParser = parserBuilder.build();
        return jwtParser.parseClaimsJws(token).getBody();
    }
}
